package thoven.achievement.net.ideapluginachievement.listener

import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.markup.HighlighterLayer
import com.intellij.openapi.editor.markup.MarkupModel
import com.intellij.openapi.editor.markup.RangeHighlighter
import com.intellij.openapi.project.Project
import thoven.achievement.net.ideapluginachievement.service.CodeStatsService

/**
 * 错误高亮监听器
 * 用于检测语法错误和编译错误，用于"麻了"成就
 */
class ErrorHighlightListener(private val project: Project) {
    
    private val LOG = logger<ErrorHighlightListener>()
    private var lastErrorCount = 0
    
    /**
     * 检测编辑器中的错误高亮
     */
    fun checkErrorHighlights(editor: Editor) {
        try {
            val document = editor.document
            val markupModel: MarkupModel = editor.markupModel
            
            // 统计错误级别的高亮
            val errorCount = markupModel.allHighlighters
                .count { highlighter ->
                    val severity = highlighter.getErrorStripeTooltip()?.toString()
                    severity != null && (
                        severity.contains("error", ignoreCase = true) ||
                        severity.contains("错误", ignoreCase = true) ||
                        severity.contains("cannot resolve", ignoreCase = true) ||
                        severity.contains("unresolved reference", ignoreCase = true)
                    )
                }
            
            // 如果错误数量增加，记录编译错误
            if (errorCount > lastErrorCount && errorCount >= 3) {
                val codeStatsService = CodeStatsService.getInstance(project)
                val newErrors = errorCount - lastErrorCount
                
                repeat(newErrors) {
                    codeStatsService.recordCompilationError()
                }
                
                LOG.debug("检测到 $newErrors 个新的编译错误")
            }
            
            lastErrorCount = errorCount
            
        } catch (e: Exception) {
            LOG.error("检测错误高亮时出错", e)
        }
    }
    
    /**
     * 重置错误计数
     */
    fun resetErrorCount() {
        lastErrorCount = 0
    }
}
